package view.item
{
	import control.manager.BitmapManager;
	import control.util.CustomLoader;
	
	import data.GameConst;
	import data.RoleVO;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.geom.Matrix;
	import flash.geom.Transform;
	import flash.net.URLRequest;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;
	import flash.utils.Dictionary;
	import flash.utils.getDefinitionByName;
	import view.role.MapObject;
	

	/**
	 * 动画播放类 
	 * @author leo
	 * 
	 */	
	public class AnimationObj extends Sprite
	{
		
		private static const PLAYER :String = "player";
		private static const NPC :String = "npc";
		private static const MONSTER :String = "monster";
		/**
		 * 图片切块的行列数 
		 */		
		private static const TILEROWCOL :int = 8;
		/**
		 * 角色容器 
		 */		
		public var roleContainer :Sprite;
		/**
		 * 角色位圖 
		 */		
		public var roleBitmap :MCBitmap;
		/**
		 * 角色位图信息列表 
		 */		
		public var roleBMDList :Array;
		/**
		 * 是否正在播放 
		 */		
		public var isPlaying :Boolean;
		/**
		 * 是否加载完动画swf
		 */		
		public var isLoadComplete :Boolean;
		/**
		 *  加载器 
		 */		
		private var loaderList :Array;
		/**
		 * 当前动作的序列
		 */		
		private var curIndex :int;
		/**
		 * 经过时间 
		 */		
		private var passTime :int;
		private var _curRoleAction :String;
		private var _curRoleDirection :int;
		/**
		 * 需要循环次数 
		 */		
		private var loopNum :int;
		/**
		 * 刷新时间，多少毫秒播放一张图片 
		 */		
		private var refreshRate :int;
		/**
		 * 当前动作的位图信息列表
		 */		
		private var curActionBMDList :Vector.<BitmapData>;
		/**
		 * 动作位图是否准备完成 
		 */		
		private var bmdIsReady :Boolean;
		/**
		 * 角色信息 
		 */		
		private var roleData :*;
		
		private var mapObj :MapObject;
		private var loaderIndex :int;
		private var total :int;
		
		/**
		 * 动画播放 
		 * @param roleData 三种角色数据都会有同样的属性/roleType/roleURL/action
		 * @param curRoleAction
		 * @param curRoleDirection
		 * 
		 */			
		public function AnimationObj(roleData :*,curRoleAction :String,curRoleDirection :int,mapObj :MapObject)
		{
			super();
			
			if(!roleData)
			{
				return;
				trace("AnimationObj roleData 角色信息为空");
			}
			this.mapObj = mapObj;
			this.roleData = roleData;
			this.curRoleAction = curRoleAction;
			this.curRoleDirection = curRoleDirection;
			if(roleData.roleURL)
			{
				this.roleBMDList = [];
				this.roleContainer = new Sprite();
				this.addChild(this.roleContainer);
				this.roleBitmap = new MCBitmap();
				this.roleBitmap.bitmapData = BitmapManager.instance.defRoleBMD;
				this.roleContainer.addChild(this.roleBitmap);
			}
			this.isLoadComplete = false;
			this.bmdIsReady = false;
			
			switch(roleData.roleType)
			{
				case PLAYER:
					loadSource();
					break;
				case NPC :
					this.roleBMDList = BitmapManager.instance.getRoleBMDList(roleData);
					//初始化完成，可以播放
					this.isLoadComplete = true;
					this.playAction(this.curRoleAction,this.curRoleDirection);
					break;
				case MONSTER :
					this.roleBMDList = BitmapManager.instance.getRoleBMDList(roleData);
					//初始化完成，可以播放
					this.isLoadComplete = true;
					this.playAction(this.curRoleAction,this.curRoleDirection);
					break;
			}
		}
		/**
		 * 播放某一个动作 
		 * @param action 默认为待机
		 * @param loop 默认为循环播放
		 * @param refreshRate 刷新频率
		 */		
		public function playAction(action :String = RoleVO.WAIT,dir :int = RoleVO.DOWN,loop :int = 0,refreshRate :int = 120):void
		{
			this.bmdIsReady = false;
			this.curRoleAction = action;
			this.curRoleDirection = dir
			this.loopNum = loop;
			this.refreshRate = refreshRate;

			this.curActionBMDList = this.roleBMDList[action + dir];
			if(this.curActionBMDList && this.curActionBMDList.length > 0)
			{
				this.bmdIsReady = true;
			}
		}
		/**
		 * 开始播放动画 
		 * 
		 */		
		private function play():void
		{
			this.passTime += GameConst.gameRefreshInterval;
			if(this.passTime >= refreshRate)
			{
				if(this.curIndex > this.curActionBMDList.length - 1)  this.curIndex = 0;
				this.roleBitmap.bitmapData = this.curActionBMDList[this.curIndex] as BitmapData;
				this.curIndex++;
				this.passTime = 0;
			}
		}
		/**
		 * 更新状态 
		 * 
		 */		
		public function update():void
		{
			if(!isLoadComplete || !bmdIsReady) return;
			play();
		}
		
		public function stopAction():void
		{
			
		}
		
		public function destroy():void
		{
			
		}
		
		/**
		 * 加载资源
		 * 
		 */		
		private function loadSource():void
		{
			if(this.roleData.action)
			{
				this.loaderList = [];
				var len :int = this.roleData.action.length;
				this.total = len;
				for(var i :int = 0; i < len; i++)
				{
					//view/source/img/role/player_wait.png
					//view/source/img/role/player_walk.png
					var str :String = this.roleData.roleURL  + this.roleData.roleType + "_" + this.roleData.action[i] + ".png";
					
					var loader :CustomLoader = new CustomLoader();
					loader.url = str;
					loader.contentLoaderInfo.addEventListener(Event.COMPLETE,loadCompleteHandler);
					loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,loadErrorHandler);
					loader.load(new URLRequest(str));
					this.loaderList.push(loader);
				}
			}
		}
		/**
		 * 加载完成 
		 * @param event
		 * 
		 */		
		private function loadCompleteHandler(event :Event = null):void
		{
			this.loaderIndex++;
			if(this.loaderIndex == this.total)
			{
				trace("角色资源加载完成");
				if(this.roleData.roleType)
				{
					getBMD();
					this.mapObj.mouseCollision.refreshRectangle();
				}else
				{
					trace("AnimationObj 角色类型为空" );
				}
				
				destroyLoaderList();
			}
		}
		
		private function loadErrorHandler(event :IOErrorEvent):void
		{
			trace("人物swf加载出错 ");
			destroyLoaderList();
		}
		
		private function getBMD():void
		{
			//现有的方向图片信息
			var frameNameAry :Array;
			var url :String;
			var actionName :String;
			var result :Vector.<BitmapData>;
			var bmd :BitmapData;
			var tileW :int;
			var tileH :int;
			var roleBitmapDict :Dictionary = BitmapManager.instance.roleBitmapDict;
			//新加载的
			if(this.loaderList && this.loaderList.length > 0)   
			{
				var len :int = this.loaderList.length;
				for(var index :int = 0; index < len; index++)
				{
					var actionIndex :int = 0;
					var loader :CustomLoader = (this.loaderList[index] as CustomLoader);
					bmd = (loader.content as Bitmap).bitmapData;
					//缓存
					roleBitmapDict[loader.url] = bmd;
					actionName = getActionName(loader.url);
					switch(actionName)
					{
						case "walk":
							frameNameAry = RoleVO.walkNameAry;
							break;
						case "wait":
							frameNameAry = RoleVO.waitNameAry;
							break;
					}
					tileW = bmd.width/TILEROWCOL;
					tileH = bmd.height/TILEROWCOL;
					for(var i :int = 0; i < TILEROWCOL; i++)
					{
						result = BitmapManager.instance.cutBitmapData(bmd,tileW,tileH,i);
						var name :String = frameNameAry[i] as String;
						this.roleBMDList[name] = result;
					}
				}
				destroyLoaderList();
			}

			//初始化完成，可以播放
			this.isLoadComplete = true;
			this.playAction(this.curRoleAction,this.curRoleDirection);

		}
		/**
		 * 获取动作名字，walk or wait or... 
		 * @param str
		 * @return 
		 * 
		 */		
		private function getActionName(str :String):String
		{
			var result :String;
			var len :int = this.roleData.action.length;
			
			for(var index :int = 0; index < len; index++)
			{
				if(str.indexOf(this.roleData.action[index]) != -1)
				{
					result = this.roleData.action[index];
				}
			}
			return result;
		}
		/**
		 * 销毁加载器 
		 */		
		private function destroyLoaderList():void
		{
			if(!this.loaderList) return;
			for(var i :int = this.loaderList.length - 1 ;i >= 0 ; i--)
			{
				var loader :CustomLoader = this.loaderList[i] as CustomLoader;
				loader.contentLoaderInfo.removeEventListener(Event.COMPLETE,loadCompleteHandler);
				loader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR,loadErrorHandler);
				loader.unload();
				loader = null;
			}
			this.loaderList = null;
		}

		/**
		 * 当前角色动作 
		 */
		public function get curRoleAction():String
		{
			return _curRoleAction;
		}

		/**
		 * @private
		 */
		public function set curRoleAction(value:String):void
		{
			_curRoleAction = value;
		}

		/**
		 * 当前角色方向 
		 */
		public function get curRoleDirection():int
		{
			return _curRoleDirection;
		}

		/**
		 * @private
		 */
		public function set curRoleDirection(value:int):void
		{
			_curRoleDirection = value;
		}


	}
}